import React, {Component} from 'react';
import './index.css';
import axios from "axios";
import PubSub from 'pubsub-js';

class Search extends Component {

    search= async () => {
        console.log('search')
        PubSub.publish('atguigu',{name:'tom',age:18})
        // //函数体，获取用户输入，
        // //连续解构赋值
        const {keyWordElement:{value:keyWord}} = this

        // //更新状态
        PubSub.publish('atguigu',{isFirst:false, isLoading:true})
        //#region 使用axios发送请求
        // 发送网络请求--接口有问题 无法请求成功-
        // axios.get(`https://api.github.com/search/user?q=${keyWord}`).then(
        //     response => {
        //         PubSub.publish('atguigu',{isFirst:false, isLoading:false, users:response.data.items})
        //     },
        //     error => {
        //         PubSub.publish('atguigu',{isFirst:false, isLoading:false, err:'请求出错了'})
        //     }
        // )
        //#endregion

        // 发送网络请求-fetch-关注分离思想
        // fetch(`https://api.github.com/search/user?q=${keyWord}`).then(
        //     response => {console.log('服务器链接成功了',response);
        //         return response.json()
        //     },
        //     error=>{console.log('服务器链接失败了',error);
        //     return new Promise(()=>{})
        //     },
        // ).then(
        //     response=>{console.log('获取数据成功了',response);},
        //     error=>{console.log('获取失败失败了',error);}
        // )
        //发送网络请求-fetch-关注分离思想(优化)
        try {
            const response = await fetch(`https://api.github.com/search/user?q=${keyWord}`)
            const data = await response.json()
            console.log(data);
            PubSub.publish('atguigu',{isFirst:false, isLoading:false, users:response.data.items})
        } catch (error) {
            console.log('请求出错',error)
            PubSub.publish('atguigu',{isFirst:false, isLoading:false, err:'请求出错了'})
        }



    }




    render() {
        return (
            <section className='jumbotron'>
                <h3 className='jumbotron-heading'>搜索 Github 用户</h3>
                <div>
                    <input ref={c=>this.keyWordElement=c} type="text" placeholder={"请输入你要搜索的名字"}/>
                    <button onClick={this.search}>搜索</button>
                </div>
            </section>
        );
    }
}

export default Search;